package com.example.seed.config.security;

import com.example.seed.entity.LoginUser;
import com.example.seed.entity.SysRole;
import com.example.seed.entity.SysUser;
import com.example.seed.error.UserException;
import com.example.seed.service.SysPermissionRepository;
import com.example.seed.service.SysUserRepository;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 自定义用户详细信息服务
 *
 * @author AAA
 * @date 2024/03/28
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserRepository userRepository;
    @Resource
    private SysPermissionRepository permissionRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userRepository.findByAccount(username);
        if (Objects.isNull(user)) {
            throw UserException.notFoundByAccount();
        }
        List<SysRole> sysRoles = user.sysRoles();

        //角色信息
        List<String> roleList = sysRoles.stream().map(it -> "ROLE_" + it.sign()).toList();

        //查询权限信息
        List<String> permissionList = permissionRepository.findPermissionSignByUserId(user.id());

        LoginUser loginUser = new LoginUser(user,
                AuthorityUtils.createAuthorityList(permissionList));


        return loginUser;
    }
}
